const WebSocket = require('ws');
const EventEmitter = require('events');
const webSocketClient = new EventEmitter();

const ws = new WebSocket('ws://127.0.0.1:8010');
ws.on('open', function open() {
    console.log('connect success')
})

ws.on('message', function incoming(message) {
    let data;
    try {
        data = JSON.parse(message);
        // console.log('websocket.js  onmessage:', data)
    } catch (e) {
        console.error('Failed to parse message:', e);
        return; // 解析失败则忽略此消息
    }

    // 确保 data 是对象，且包含所需属性
    if (data && typeof data === 'object') {
        let event = data.event || 'defaultEvent'; // 用合适的默认事件替代 'defaultEvent'
        let dataContent = data.data || '';
        let fromCode = data.fromCode || '';

        webSocketClient.emit(event, data);
    } else {
        console.warn('Received malformed data:', data);
    }
});


function send(event, data) {
    console.log('send to websocket event:', event)
    console.log('send to websocket data:', data)
    ws.send(JSON.stringify({event, data}))
}

function sendData(data) {
    ws.send(data)
}

function invoke(event, data, answerEvent) {
    return new Promise((resolve, reject) => {
        send(event, data)
        webSocketClient.once(answerEvent, resolve)
        setTimeout(() => {
            reject('timeout')
        }, 5000)
    })
}

function disconnect() {
    if (ws.readyState === WebSocket.OPEN){
        ws.close()
    }
    webSocketClient.removeAllListeners()
}

function connect(event, data, answerEvent){
    return new Promise((resolve, reject) => {
        send(event, data)
        webSocketClient.once(answerEvent, resolve)
        setTimeout(() => {
            reject('timeout')
        }, 5000)
    })
}

webSocketClient.connect = connect
webSocketClient.disconnect = disconnect
webSocketClient.send = send
webSocketClient.invoke = invoke
webSocketClient.sendData = sendData

module.exports = webSocketClient
